﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using WinnerCMS.BLL;
using WinnerCMS.BLL.Rights;
using WinnerCMS.Common;
namespace WinnerCMS.HttpModule
{
    /// <summary>
    /// 权限检查
    /// </summary>
    /// <remarks>IReadOnlySessionState、IRequiresSessionState</remarks>
    public class PowerChecker : System.Web.IHttpModule, IReadOnlySessionState
    {
        public PowerChecker() { }
        public void Dispose() { }
        public void Init(HttpApplication app)
        {
            //建立安全模块 
            app.AcquireRequestState += (new EventHandler(this.BeginRequest));
             
        }
        private void BeginRequest(object o, EventArgs e)
        {
            HttpApplication app = o as HttpApplication;
            HttpContext context = app.Context;


             
            CheckLogined(context);
        }

        #region 检查登陆
        /// <summary>
        /// 检查登陆
        /// </summary>
        /// <param name="content"></param>
        private static void CheckLogined(HttpContext content)
        {
            string path = content.Request.Path;
            if (content.Request.CurrentExecutionFilePathExtension.Equals(".aspx", StringComparison.CurrentCultureIgnoreCase) == false)
            {
                return;
            }
            

            string backGroundPath = WebConfig.BackGroundPath.Replace("\\", "/").Replace("~", "");
            //只检查后台目录或者会员目录
            if (path.StartsWith(backGroundPath, StringComparison.CurrentCultureIgnoreCase))
            {
                if (MyCollections.Contain(path, RightsControlManage.HuLue))
                {
                    return;
                }
                if (!content.User.Identity.IsAuthenticated)
                {
                    content.Response.Redirect("~" + backGroundPath + "Login.aspx");
                }
                else
                {
                    RightsControlManage.CheckUrlAccess(content);
                }
            }
            else if (path.StartsWith("/member", StringComparison.CurrentCultureIgnoreCase))
            {
                if (MyCollections.Contain(path, RightsControlManage.HuLue))
                {
                    return;
                }
                if (!content.User.Identity.IsAuthenticated)
                {
                    content.Response.Redirect("~/Member/Login.aspx?redirectURL=" + content.Server.UrlEncode(content.Request.Url.ToString()));
                }
            }
        }
        #endregion
         
    }
}